<?php

namespace app\api\service;

use app\store\model\ApplyOfflineShop;
use app\store\model\OfflineShopGoods;
use think\facade\Db;

class ShopsService
{
  
   

    /**
     * 商品列表
     */
    public static function goodsList($offline_shop_id, $store_id)
    {
        $goods = new OfflineShopGoods();
        return $goods->where(['offline_shop_id' => $offline_shop_id, 'status' => 1, 'store_id' => $store_id])
            ->withAttr('img', function ($value) {
                return request()->domain() . $value;
            })
            ->order('create_time', 'desc')->paginate(10);
    }

    /**
     * 商品信息
     */
    public static function goodsInfo($gid, $store_id)
    {
        $goods = new OfflineShopGoods();
        return $goods->where(['id' => $gid, 'store_id' => $store_id])->find();
    }

    public static function label($data)
    {
        return Db::name('offline_shop_label')
        ->where('store_id', $data['store_id'])
        ->where('status', 1)
        ->where('delete_time', 0)
        ->order('sort', 'desc')->select();
    }

    /**
     * 删除商品
     */
    public static function delGoods($gid, $data)
    {
        $goods = new OfflineShopGoods();
        return $goods->where(['id' => $gid, 'offline_shop_id' => $data['offline_shop_id']])->update(['delete_time' => time()]);
    }

    /**
     * 编辑商品
     */
    public static function editGoods($gid, $data)
    {
        $goods = OfflineShopGoods::find($gid);
        $data['img'] = parse_url($data['img'])['path'];
        return $goods->allowField(['img', 'name', 'status', 'sell_price', 'market_price', 'desc'])->save($data);
    }

    /**
     * 添加商品
     */
    public static function saveGoods($data)
    {
        $goods = new OfflineShopGoods();
        $data['img'] = parse_url($data['img'])['path'];
        return $goods->allowField(['img', 'name', 'store_id', 'status', 'offline_shop_id', 'desc', 'sell_price', 'market_price'])->save($data);
    }

    /**
     * 商圈列表
     */
    public static function offlineShops($param)
    {
        if (empty($param['lat']) || empty($param['lng'])) {
            $lat = '34.211850';
            $lng = '108.995210';
        } else {
            $lat = $param['lat'];
            $lng = $param['lng'];
        }
        $keyword = empty($param['keyword']) ? '' : $param['keyword'];
        // $is_recommended = empty($param['is_recommended'])?'':$param['is_recommended'];
        $label_id = empty($param['label_id'])?'':$param['label_id'];
        $category_id = empty($param['category_id']) ? '' : $param['category_id'];
        $rst = Db::name('offline_shop')
            ->where(['store_id' => $param['store_id'], 'status' => 2, 'delete_time' => 0, 's_status'=>1])
            ->field("*,(6378.138 * 2 * asin(sqrt(pow(sin((lat * pi() / 180 - " . $lat . " * pi() / 180) / 2),2) + cos(lat * pi() / 180) * cos(" . $lat . " * pi() / 180) * pow(sin((lng * pi() / 180 - " . $lng . " * pi() / 180) / 2),2))) * 1000) as distance")
            ->order('distance')
            ->withAttr('business_license', function ($value) {
                return request()->domain() . $value;
            })
            ->withAttr('bg_imgs', function ($value) {
                $bg_img = explode(',', $value);
                foreach ($bg_img as $k => $v) {
                    $bg_img[$k] = request()->domain() . $v;
                }
                return $bg_img;
            })
            ->withAttr('logo', function ($value) {
                return request()->domain() . $value;
            });
        if ($keyword) {
            $rst = $rst->where('shop_name', 'like', '%' . $keyword . '%');
        }
        if ($label_id) {
            $default_status = Db::name('offline_shop_label')->where(['store_id'=>$param['store_id'],
                'id'=>$label_id, 'status'=>1,'delete_time'=>0])->value('default_status');
            if ($default_status == 1) {
                $rst = $rst->where('label_id', $label_id);
            }
            if ($default_status == 2) {
                $rst = $rst->where('is_recommended', 2);
            }
        }
        if ($category_id) {
            $rst = $rst->where('category_id', $category_id);
        }
        $rst = $rst->
        paginate(10)->each(function ($item) {
            $item['distance'] = bcdiv($item['distance'], 1000, 2);
            $item['distance_unit'] = 'km';
            if ($item['label_id']) {
                $item['label'] = Db::name('offline_shop_label')
                ->where('status', 1)->where('delete_time',0)
                ->where('id', $item['label_id'])->value('name');
            } else{
                $item['label'] = '';
            }
            return $item;
        });
        return $rst;
    }

    /**
     * 商圈分类
     */
    public static function category($param)
    {
        $rst = Db::name('offline_shop_category')
        ->order('sort', 'desc')
        ->withAttr('icon', function ($value) {
            return request()->domain() . $value;
        })
        ->where(['store_id' => $param['store_id'], 'status' => 1, 'delete_time'=>0])->select();
        return $rst;
    }

    /**
     * 其他人的店铺信息
     */
    public static function findShopInfo($shop_id, $store_id)
    {
        $rst = Db::name('offline_shop')
            ->where(['id' => $shop_id, 'delete_time' => 0,  'store_id' => $store_id])
            ->withAttr('business_license', function ($value) {
                return request()->domain() . $value;
            })
            ->withAttr('bg_imgs', function ($value) {
                $bg_img = explode(',', $value);
                foreach ($bg_img as $k => $v) {
                    $bg_img[$k] = request()->domain() . $v;
                }
                return implode(',', $bg_img);
            })
            ->withAttr('logo', function ($value) {
                return request()->domain() . $value;
            })->find();
        if (!empty($rst)) {
            $rst['bg_imgs'] = explode(',', $rst['bg_imgs']);
        }
        return $rst;
    }

    /**
     * 我的店铺信息
     */
    public static function getShopInfo($uid, $store_id)
    {
        $rst = Db::name('offline_shop')->where(['uid' => $uid, 'delete_time' => 0, 'store_id' => $store_id])
            ->withAttr('business_license', function ($value) {
                return request()->domain() . $value;
            })
            ->withAttr('bg_imgs', function ($value) {
                $bg_img = explode(',', $value);
                foreach ($bg_img as $k => $v) {
                    $bg_img[$k] = request()->domain() . $v;
                }
                return implode(',', $bg_img);
            })
            ->withAttr('logo', function ($value) {
                return request()->domain() . $value;
            })
            ->order('create_time', 'desc')
            ->find();
        if (!empty($rst)) {
            $rst['bg_imgs'] = explode(',', $rst['bg_imgs']);
        }
        return $rst;
    }
 

    /**
     * 提交店铺
     */
    public static function saveShop($data)
    {
        $data['logo'] = parse_url($data['logo'])['path'];
        $data['business_license'] = parse_url($data['business_license'])['path'];
        $bg_img = explode(',', $data['bg_imgs']);
        foreach ($bg_img as $k => $v) {
            $bg_img[$k] = parse_url($v)['path'];
        }
        $data['bg_imgs'] = implode(',', $bg_img);
        $data['create_time'] = time();
      
        Db::startTrans();
        try {
            $shop_id = Db::name('offline_shop')->insertGetId($data);
            $data['type'] = 1;
            $data['desc'] = '店铺入驻';
            $data['offline_shop_id'] = $shop_id;
            Db::name('apply_offline_shop')->insert($data);
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            // echo $e->getMessage();exit;
            Db::rollback();
            return false;
        }
        return true;
    }

}
